package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.NcInputChicken;
import com.ruoyi.system.domain.NcOrderCf;
import com.ruoyi.system.domain.NcOutputChicken;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 鸡出库 信息操作处理
 *
 * @author ruoyi
 * @date 2019-09-09
 */
@Controller
@RequestMapping("/system/ncOutputChicken")
public class NcOutputChickenController extends BaseController {
    private String prefix = "system/ncOutputChicken";
    private String chickenPrefix="system/screen";

    @Autowired
    private INcOutputChickenService ncOutputChickenService;

    @Autowired
    private INcOrderCfService orderCfService;
    @Autowired
    private ISysDictDataService dataService;
    @Autowired
    private INcFeedService feedService;
    @Autowired
    private INcInputChickenService inputChickenService;
    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("system:ncOutputChicken:view")
    @GetMapping()
    public String ncOutputChicken(ModelMap map) {
        Integer zFfeed = feedService.stockAmout(1);

        map.put("zFfeed", zFfeed);

        Integer fFfeed = feedService.stockAmout(2);

        map.put("fFfeed", fFfeed);

        Integer chickStackAamount = inputChickenService.chickenStackAmount();

        map.put("chickStackAamount", chickStackAamount);
        return prefix + "/ncOutputChicken";
    }

    @GetMapping("/ncOutputChickenAll")
    public String ncOutputChickenAll(ModelMap map) {
        Integer zFfeed = feedService.stockAmout(1);

        map.put("zFfeed", zFfeed);

        Integer fFfeed = feedService.stockAmout(2);

        map.put("fFfeed", fFfeed);

        Integer chickStackAamount = inputChickenService.chickenStackAmount();

        map.put("chickStackAamount", chickStackAamount);
        return prefix + "/ncOutputChicken-all";
    }


    /**
     * 查询鸡出库列表
     */
    @RequiresPermissions("system:ncOutputChicken:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcOutputChicken ncOutputChicken, ModelMap map) {
        startPage();

        List<NcOutputChicken> list = ncOutputChickenService.selectNcOutputChickenList(ncOutputChicken);
        return getDataTable(list);
    }

    /**
     * 查询鸡出库列表
     */
    @PostMapping("/listTodays")
    @ResponseBody
    public TableDataInfo listTodays(NcOutputChicken ncOutputChicken, String today, ModelMap map, Integer type) {
        startPage();
        ncOutputChicken.getParams().put("today", today);
        ncOutputChicken.getParams().put("type", type);
        List<NcOutputChicken> list = ncOutputChickenService.selectNcOutputChickenList(ncOutputChicken);
        return getDataTable(list);
    }


    /**
     * 导出鸡出库列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcOutputChicken ncOutputChicken) {
        List<NcOutputChicken> list = ncOutputChickenService.selectNcOutputChickenList(ncOutputChicken);
        ExcelUtil<NcOutputChicken> util = new ExcelUtil<NcOutputChicken>(NcOutputChicken.class);
        return util.exportExcel(list, "鸡出库订单");
    }

    /**
     * 新增鸡出库
     */
    @GetMapping("/add")
    public String add(ModelMap map) {
        NcInputChicken inputChicken = new NcInputChicken();
        inputChicken.getParams().put("stock", 1);
        List<NcInputChicken> inputChickenList = inputChickenService.selectNcInputChickenList(inputChicken);
        map.put("inputChicken", inputChickenList);
        SysUser user=new SysUser();
        user.setDelFlag("0");
        user.setDelFlag("0");
        List<SysUser> userList=userService.selectUserList(user);
        map.put("userList",userList);
        return prefix + "/add";
    }

    /**
     * 新增保存鸡出库
     */
    @RequiresPermissions("system:ncOutputChicken:add")
    @Log(title = "鸡出库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    @ResponseBody
    public AjaxResult addSave(Integer outputId,NcOutputChicken ncOutputChicken) {
        ncOutputChicken.setCreateBy(ShiroUtils.getLoginName());
        ncOutputChicken.setCreateTime(new Date());
        ncOutputChicken.setOutputStatus(Long.valueOf(2));
        //获取所选批次的库存
        NcInputChicken chicken = inputChickenService.selectNcInputChickenById(outputId);
        NcInputChicken inputChicken = new NcInputChicken();
        inputChicken.setInputId(outputId);
        inputChicken.setStackAmount(chicken.getStackAmount()-ncOutputChicken.getOutputAmount());
        inputChickenService.updateNcInputChicken(inputChicken);
        ncOutputChickenService.insertNcOutputChicken(ncOutputChicken);
        return AjaxResult.success("添加成功！");
    }

    /**
     * 修改鸡出库
     */
    @GetMapping("/edit/{outputId}")
    public String edit(@PathVariable("outputId") Integer outputId, ModelMap mmap) {
        NcOutputChicken ncOutputChicken = ncOutputChickenService.selectNcOutputChickenById(outputId);
        mmap.put("ncOutputChicken", ncOutputChicken);
        NcInputChicken inputChicken = new NcInputChicken();
        inputChicken.getParams().put("stock", 1);
        List<NcInputChicken> inputChickenList = inputChickenService.selectNcInputChickenList(inputChicken);
        mmap.put("inputChicken", inputChickenList);
        return prefix + "/edit";
    }

    /**
     * 修改保存鸡出库
     */
    @RequiresPermissions("system:ncOutputChicken:edit")
    @Log(title = "鸡出库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(NcOutputChicken ncOutputChicken, Integer inputId) {
        NcInputChicken chicken = inputChickenService.selectNcInputChickenById(inputId);
        NcInputChicken inputChicken = new NcInputChicken();
        Integer outputId = ncOutputChicken.getOutputId();
        //获取之前的出库数量
        Integer outputAmount = ncOutputChickenService.selectNcOutputChickenById(outputId).getOutputAmount();
        //获取编辑的出库数量
        Integer editOutputAmount = ncOutputChicken.getOutputAmount();
        inputChicken.setInputId(inputId);
        if (editOutputAmount >= outputAmount) {
            inputChicken.setStackAmount(chicken.getStackAmount() - (editOutputAmount - outputAmount));
        } else {
            inputChicken.setStackAmount(chicken.getStackAmount() + (outputAmount - editOutputAmount));
        }
        inputChickenService.updateNcInputChicken(inputChicken);
        NcOrderCf ncOrderCf = new NcOrderCf();
        ncOrderCf.setRequestAmount(BigDecimal.valueOf(ncOutputChicken.getRequestAmount()));
        ncOrderCf.setCforderId(Long.valueOf(ncOutputChicken.getCforderId()));
        orderCfService.updateNcOrderCf(ncOrderCf);
        return toAjax(ncOutputChickenService.updateNcOutputChicken(ncOutputChicken));
    }

    /**
     * 删除鸡出库
     */
    @RequiresPermissions("system:ncOutputChicken:remove")
    @Log(title = "鸡出库", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncOutputChickenService.deleteNcOutputChickenByIds(ids));
    }

    /**
     * 确认
     */
    @GetMapping("/enter/{id}/{requestAmount}")
    public String enter(@PathVariable("id") int id, ModelMap map, @PathVariable("requestAmount") String requestAmount) {
        NcInputChicken inputChicken = new NcInputChicken();
        inputChicken.getParams().put("stock", 1);
        List<NcInputChicken> inputChickenList = inputChickenService.selectNcInputChickenList(inputChicken);
        map.put("cforderId", id);
        map.put("name", ShiroUtils.getLoginName());
        map.put("inputChicken", inputChickenList);
        map.put("requestAmount", Long.valueOf(requestAmount));
        return prefix + "/enter";
    }

    /**
     * 查询鸡出库工作记录列表
     */
    @RequiresPermissions("system:ncOutputChicken:selectChicken")
    @PostMapping("/selectChicken")
    @ResponseBody
    public TableDataInfo selectChicken(NcOrderCf ncOrderCf) {
        startPage();
        List<NcOrderCf> list = orderCfService.selectNcOrderCfList(ncOrderCf);
        return getDataTable(list);
    }

    /**
     * 新增保存鸡出库工作记录
     */
    @RequiresPermissions("system:ncOutputChicken:addWork")
    @Log(title = "鸡出库", businessType = BusinessType.UPDATE)
    @PostMapping("/addWork")
    @ResponseBody
    @Transactional
    public AjaxResult addWork(NcOutputChicken ncOutputChicken, Integer inputId) {
        NcInputChicken chickenAmount = inputChickenService.selectNcInputChickenById(inputId);
        NcInputChicken chicken = new NcInputChicken();
        chicken.setInputId(inputId);
        chicken.setStackAmount(chickenAmount.getStackAmount() - ncOutputChicken.getOutputAmount());
        //修改库存
        inputChickenService.updateNcInputChicken(chicken);
        ncOutputChicken.setOutputTime(new Date());
        ncOutputChicken.setOutputStatus(Long.valueOf(2));
        //修改订单状态
        NcOrderCf order = new NcOrderCf();
        order.setCforderId(ncOutputChicken.getCforderId());
        order.setCforderStatus("9");
        orderCfService.updateNcOrderCf(order);
        return toAjax(ncOutputChickenService.insertNcOutputChicken(ncOutputChicken));


    }

    /**
     * 确认生成入库单
     */
    @Log(title = "确认生成入库单", businessType = BusinessType.OTHER)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids) {
        SysUser user = ShiroUtils.getSysUser();
        return toAjax(ncOutputChickenService.createOrderByIds(ids, user));
    }

    @GetMapping("/chicken")
    public String confirmTable(NcOutputChicken ncOutputChicken, String beginTime, String endTime, ModelMap map, Integer type) throws ParseException {
        if (StringUtils.isNotEmpty(beginTime)) {
            ncOutputChicken.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            ncOutputChicken.getParams().put("endTime", endTime);
        }
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        ncOutputChickenService.setChickenTypes(map, ncOutputChicken, type, 1);
        return prefix + "/chickenManage";

    }

    /**
     * @param dataSpan 时间跨度 1:年 2：月 3：日
     * @return
     */
    @PostMapping("/chickenQuery")
    @ResponseBody
    public TableDataInfo chickenQuery(Integer dataSpan, String beginTime, String endTime, Integer outputType) {
        //

        List<Map> list = ncOutputChickenService.selectCountByTime(dataSpan, beginTime, endTime, outputType);
        return getDataTable(list);
    }

    /**
     鸡舍大屏产肉量
     */
    @GetMapping("/jishe1")
    public String feedAmounts(ModelMap map) {
        Calendar cal = Calendar.getInstance();
        //获取最近7天的数据
        List<Double> chicken = new ArrayList<Double>();
        NcOutputChicken ncOutputChicken = new NcOutputChicken();
        ncOutputChicken.setOutputStatus(Long.valueOf(3));
        String[] last7Day = last7Day(cal);
        for (int i = 0; i < last7Day.length; i++) {
            ncOutputChicken.getParams().put("dateSpanDay", last7Day[i]);
            double amount = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken);
            chicken.add(amount);
        }
        map.put("chicken", chicken);
        map.put("date", last7Day);
        //今天以及昨天同比
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String time2 = format2.format(Calendar.getInstance().getTime());
        ncOutputChicken.getParams().put("dateSpanDay", time2);
        double todayAmount = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken);
        map.put("todayAmount", todayAmount);
        //获取昨天
        NcOutputChicken ncOutputChicken1 = new NcOutputChicken();
        ncOutputChicken1.setOutputStatus(Long.valueOf(3));
        Calendar cal1=Calendar.getInstance();
        cal1.add(Calendar.DATE, -1);
        String yesterday = format2.format(cal1.getTime());
        ncOutputChicken1.getParams().put("dateSpanDay", yesterday);
        double yesterdayAmount = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken1);
        if(yesterdayAmount != 0){
            map.put("dayRatio", new DecimalFormat("0.00").format(Double.valueOf((todayAmount - yesterdayAmount) / yesterdayAmount * 100)));
        }
        else{
            map.put("dayRatio",new DecimalFormat("0.00").format((double)Math.round(todayAmount*100)));

        }
        //本月以及上个月同比
        NcOutputChicken ncOutputChicken2 = new NcOutputChicken();
        ncOutputChicken2.setOutputStatus(Long.valueOf(3));
        Calendar cal2=Calendar.getInstance();
        String month = null;
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            month = cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        }
        else {
            month = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        ncOutputChicken2.getParams().put("dateSpanMonth", month);
        double monthAmount = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken2);
        //上个月
        String lastMonth = null;
        cal2.add(Calendar.MONTH,-1);
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            lastMonth = cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        } else {
            lastMonth = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        ncOutputChicken2.getParams().put("dateSpanMonth", lastMonth);
        double laMonth = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken2);
        map.put("month", monthAmount);
        if(laMonth != 0){
            map.put("monthRatio", new DecimalFormat("0.00").format(Double.valueOf((monthAmount - laMonth) / laMonth * 100)));
        }
        else{
            map.put("monthRatio", new DecimalFormat("0.00").format((double)Math.round(monthAmount*100)));
        }
        //本年以及去年月同比
        NcOutputChicken ncOutputChicken3 = new NcOutputChicken();
        ncOutputChicken3.setOutputStatus(Long.valueOf(3));
        String year = cal2.get(Calendar.YEAR) + "";
        ncOutputChicken3.getParams().put("dateSpanYear", year);
        double thisYear = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken3);
        cal2.add(Calendar.YEAR,-1);
        String year1 = cal2.get(Calendar.YEAR) + "";
        ncOutputChicken3.getParams().put("dateSpanYear", year1);
        double lastYear = ncOutputChickenService.selectNcOutputMonthAmount(ncOutputChicken3);
        map.put("year", thisYear);
        if(lastYear != 0){
            map.put("yearRatio", new DecimalFormat("0.00").format(Double.valueOf((thisYear - lastYear) / lastYear * 100)));
        }
        else{
            map.put("yearRatio", new DecimalFormat("0.00").format((double)Math.round(thisYear*100)));
        }
        return chickenPrefix+"/chickenRou";
    }

    //产生最近一周的时间
    public String[] last7Day(Calendar cal) {
        String[] last7Day = new String[7];
        for (int i = 0; i < 7; i++) {
            if (cal.get(Calendar.MONTH) + 1 < 10) {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }
            } else {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }

            }
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); //逐次往前推1天*/

        }
        return last7Day;
    }



}
